package com.lucien.TestDemo;

public class TestSparseArray {
    public static void main(String[] args) {
        //0：没有棋子  1：黑色棋子  2：白色棋子
        int [][] chessArr = new int [11][11];
        chessArr[2][5]=1;
        chessArr[6][7]=2;
        chessArr[4][1]=1;
        chessArr[8][3]=2;

        //原二维数组
        for (int []row : chessArr){
            for (int data : row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        int sum =0;
        for (int i = 0; i < chessArr.length; i++) {
            for (int j = 0; j < chessArr.length; j++) {
                if (chessArr[i][j] != 0){
                    sum++;
                }
            }
        }

        int [][] sparsearr = new int [sum+1][3];
        sparsearr[0][0] = 11;
        sparsearr[0][1] = 11;
        sparsearr[0][2] = sum;
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0){
                    count++;
                    sparsearr[count][0]=i;
                    sparsearr[count][1]=j;
                    sparsearr[count][2]=chessArr[i][j];
                }
            }
        }
        System.out.println("稀疏数组");
        System.out.println("行  列  值");
        for (int i = 0; i < sparsearr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n",sparsearr[i][0],sparsearr[i][1],sparsearr[i][2]);
        }


        int [][]chessarr2 = new int [sparsearr[0][0]][sparsearr[0][1]];

        for (int i = 1; i < sparsearr.length; i++) {
            chessarr2[sparsearr[i][0]][sparsearr[i][1]]=sparsearr[i][2];
        }

        System.out.println("恢复后得二维数组");
        for (int [] row : chessarr2){
            for (int data : row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }
}
